package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.CategoryDto;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.common.utils.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;



/**
 * @author syf
 * @version 1.0
 * @date 2019/07/30 21:44
 * @Description TODO:分类管理
 */
@Service
@Transactional //事务控制
public class CategoryService  {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     *根据父类的pid查询当前父id下的所有子类
     * @param pid
     * @return
     */
    public List<CategoryDto> findCategoryByPid(Long pid) {

        //查询条件，mapper会把对象中 非空属性作为查询条件
        Category record =new Category();
        record.setParentId(pid);
        List<Category> categories = categoryMapper.select(record);
        //判断结果
        if (CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);

        }
        //使用自定义工具类，把category集合转为DTO集合
        return BeanHelper.copyWithCollection(categories,CategoryDto.class);

    }

    /**
     * 根据分类id集合查询分类集合
     * @param ids
     * @return
     */
    public List<CategoryDto> findListByIds(List<Long> ids) {

        List<Category> categories = categoryMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(categories)){
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(categories,CategoryDto.class);
    }
}
